<?php
class Default_Model_Account extends Zend_Db_Table{

	protected $_name = USER_TABLE;
	protected $_primary = 'user_id';

	private $USER_NAME = "username";
	private $USER_PWD = "password";
	private $USER_ROLE = "role";
	private  $ADMIN = 1;

	protected $db;
	protected  $auth;

	public function __construct(){
		$this->auth = Zend_Auth::getInstance();
		//Goi ket noi voi Zend Db
		$this->db = Zend_Registry::get('connectDB');
	}

	protected $_messageError = null;

	public function hasIdentity() {
		if($this->auth->hasIdentity())
			return true;
		else
			return false;
	}

	public function login($arrParam = null){
		try {
			// Khai bao bang va 2 cot se su dung so sanh trong qua tronh login
			$authAdapter = new Zend_Auth_Adapter_DbTable($this->db);
			$authAdapter->setTableName(USER_TABLE)
			->setIdentityColumn($this->USER_NAME)
			->setCredentialColumn($this->USER_PWD);
			$select = $authAdapter->getDbSelect();
			//$select->where($this->USER_ROLE.' = ' . $this->ADMIN);

			$username = $arrParam['username'];
			$password = $arrParam['password'];
			$authAdapter->setIdentity($username);
			$authAdapter->setCredential(md5($password));

			//Lay ket qua truy van cua Zend_Auth
			$result = $this->auth->authenticate($authAdapter);

			$flag = false;
			if(!$result->isValid()){
				$error = $result->getMessages();
				$this->_messageError = current($error);
			}else{
				//Lay nhung du lieu can thiet trong bang users neu login thanh cong
				$omitColumns = array($this->USER_PWD);
				$data = $authAdapter->getResultRowObject(null,$omitColumns);
				//Luu  nhung du lieu cua member vao session
				$this->auth->getStorage()->write($data);
				$flag = true;
			}
			return $flag;
		} catch (Exception $e) {
			$this->_messageError = $e->getMessage();
		}
	}

	public function logout(){
		$this->auth->clearIdentity();
	}
	
	public function getName() {
		 if($this->auth->hasIdentity()){
		 	return $this->auth->getIdentity()->Name;
		 }
	}
	
	public function getFullName() {
		if($this->auth->hasIdentity()){
			return $this->auth->getIdentity()->fullname;
		}
	}
	
	public function getUserName() {
		if($this->auth->hasIdentity()){
			return $this->auth->getIdentity()->username;
		}
	}
	
	public function getProfilePicture() {
		if($this->auth->hasIdentity()){
			return $this->auth->getIdentity()->profile_picture;
		}
	}
	
	public function getEmail() {
		if($this->auth->hasIdentity()){
			return $this->auth->getIdentity()->email;
		}
	}
	
	public function getUserId() {
		if($this->auth->hasIdentity()){
			return $this->auth->getIdentity()->user_id;
		}
	}
	
	public function getRole() {
		if($this->auth->hasIdentity()){
			return $this->auth->getIdentity()->role;
		}
	}
	
	public function getError(){
		return $this->_messageError;
	}
}